const util = require('../../utils/util')
let p

Page({

	data: {
		libGroup: 'choose',
		searchContent: '',
		searchDone: false,
		resultList: [],
		loanList: [],
		bookInfo: false,
		pageDone: false,
		getLoanDone: false
	},

	temp: {
		pageIndex: 0,
		searchMode: 0,
		searchContent: ''
	},

	onLoad: function (options) {
		p = this
		util.userLogin({
			p,
			scene: 'other',
			complete: () => {
				util.showNotices(p)
			},
			fail: (title, msg) => {
				wx.navigateBack({
					delta: 1
				})
				util.error(title, msg)
			},
			notBind: () => {
				util.modal('绑定提示', '只有登录和绑定身份后才能使用此功能哦，即将跳转到主页', () => {
					wx.switchTab({
						url: '/pages/home/home'
					})
				})
			}
		})
	},

	onUnload: () => {
		util.unloadPage('library')
	},

	openSearchGroup: () => {
		wx.setNavigationBarTitle({
			title: '',
		})
		p.setData({
			libGroup: 'search'
		})
	},

	inputSearch: (e) => {
		p.setData({
			searchContent: e.detail.value
		})
	},

	search: (e) => {
		const searchMode = e.currentTarget.dataset.mode
		const searchContent = p.data.searchContent
		util.loading('搜索中')
		p.searchBook(searchMode, searchContent, 0)
	},

	searchBook: (searchMode, searchContent, pageIndex) => {
		p.setData({
			searchContent: ''
		})
		util.request({
			source: 'library',
			uri: `sys/library/search/${searchMode}/${encodeURIComponent(searchContent)}`,
			data: {
				page: pageIndex,
				session: util.globalData('session')
			},
			success: data => {
				if (p.temp.searchMode == searchMode && p.temp.searchContent == searchContent) {
					p.data.resultList = p.data.resultList.concat(data)
				}
				else {
					p.temp.pageIndex = 0
					p.data.resultList = data
					p.setData({
						pageDone: false
					})
				}
				p.temp.searchMode = searchMode
				p.temp.searchContent = searchContent
				console.log(p.data.resultList)
				if (data.length != 20)
					p.setData({ pageDone: true })
				p.setData({
					searchDone: true,
					resultList: p.data.resultList
				})
				wx.hideToast()
			},
			fail: (code, msg) => {
				wx.hideToast()
				util.error('搜索失败', util.errorHandler(code, msg))
			}
		})
	},

	showMore: () => {
		p.temp.pageIndex++
		const { searchMode, searchContent, pageIndex} = p.temp
		util.loading('获取中')
		p.searchBook(searchMode, searchContent, pageIndex)
	},

	openLoanGroup: () => {
		wx.setNavigationBarTitle({
			title: '我的借阅',
		})
		p.getLoanList({
			success: loanList => {
				p.setLoanList(loanList)
			},
			fail: (code, msg) => {
				util.error('同步失败', util.errorHandler(code, msg))
			}
		})
		p.setData({
			libGroup: 'loan'
		})
	},

	getLoanList: obj => {
		const {success, fail, sync} = obj
		util.loading('同步中')
		util.request({
			source: 'library',
			method: sync ? 'put' : 'get',
			uri: `user/${util.getUserType()}/library/loan`,
			data: {
				session: util.globalData('session')
			},
			success: loanList => {
				success(loanList)
			},
			fail: (code, msg) => {
				wx.hideToast()
				p.setData({ getLoanDone: true })
				fail(code, msg)
			}
		})
	},

	setLoanList: (loanList) => {
		p.setData({
			loanList
		})
		p.setData({ getLoanDone: true })
		wx.hideToast()
	},

	showBookInfo: (e) => {
		const bookId = e.currentTarget.dataset.bookid
		util.loading('请稍候')
		util.request({
			source: 'library',
			method: 'get',
			uri: `sys/library/book/${bookId}`,
			data: {
				session: util.globalData('session')
			},
			success: (bookInfo) => {
				console.log(bookInfo)
				p.setData({
					bookInfo
				})
				wx.hideToast()
			},
			fail: (code, msg) => {
				util.error('获取失败', util.errorHandler(code, msg))
				wx.hideToast()
			}
		})
	},

	showLoanBookInfo: (e) => {
		const index = e.currentTarget.dataset.index
		const { bookId, bookAddress, bookNum, bookLoanDate, bookReturnDate, bookExpire, bookReloanCount, bookMaxReloanCount } = p.data.loanList[index]
		util.loading('获取中')
		util.request({
			source: 'library',
			method: 'get',
			uri: `user/${util.getUserType()}/library/book/${bookId}`,
			data: {
				session: util.globalData('session')
			},
			success: (bookInfo) => {
				console.log(bookInfo, bookReloanCount, bookMaxReloanCount)
				Object.assign(bookInfo, {
					bookNum,
					bookAddress,
					bookLoanDate,
					bookReturnDate,
					bookExpire,
					notReloan: bookExpire == 1 || bookReloanCount >= bookMaxReloanCount
				})
				console.log(bookInfo)
				p.setData({
					bookInfo
				})
				wx.hideToast()
			},
			fail: (code, msg) => {
				util.error('获取失败', util.errorHandler(code, msg))
				wx.hideToast()
			}
		})
	},

	closeLoanBookInfo: () => {
		p.setData({
			bookInfo: false
		})
	},

	reloanBook: (e) => {
		const bookNum = e.currentTarget.dataset.booknum
		util.loading('续借中')
		util.request({
			source: 'library',
			method: 'put',
			uri: `user/${util.getUserType()}/library/reloan/${bookNum}`,
			data: {
				session: util.globalData('session')
			},
			success: () => {
				util.modal('续借成功', '此书的归还日期已成功延长一个月', () => {
					p.setData({
						loanList: [],
						bookInfo: false
					})
					p.getLoanList({
						sync: true,
						success: loanList => {
							p.setLoanList(loanList)
						},
						fail: (code, msg) => {
							util.error('同步失败', util.errorHandler(code, msg))
						}
					})
				})
			},
			fail: (code, msg) => {
				wx.hideToast()
				util.error('续借失败', util.errorHandler(code, msg))
			}
		})
	},

	showReturnDate: (e) => {
		const index = e.currentTarget.dataset.index
		const {bookInfo} = p.data
		const date = new Date(bookInfo.bookOutList[index].bookReturnDate * 1000)
		util.modal('归还时间', `此书借阅人应在${date.getFullYear()}年${date.getMonth()}月${date.getDate()}日前归还本书`)
	},

	onPullDownRefresh: () => {
		if(p.data.libGroup == 'loan') {
			wx.showModal({
				title: '同步最新记录',
				content: '是否现在同步您最新的借阅记录？',
				success: (res) => {
					if(res.confirm) {
						p.getLoanList({
							sync: true,
							success: loanList => {
								p.setLoanList(loanList)
								wx.stopPullDownRefresh()
							},
							fail: (code, msg) => {
								util.error('同步失败', util.errorHandler(code, msg))
								wx.stopPullDownRefresh()
							}
						})
					}
					else
						wx.stopPullDownRefresh()
				}
			})
		}
		else
			wx.stopPullDownRefresh()
	}

})